using System.Collections.Generic;
using GameKitUnity.Core;
using UnityEngine;

namespace OneGame.Gameplay.Weapon
{
    public class SwordController : MonoBehaviour, IWeapon
    {
        [SerializeField]
        private Transform raycastRoot;

        [SerializeField]
        private float raycastDistance = 1f;

        [SerializeField]
        private LayerMask layerMask;

        [SerializeField]
        private float damageDelay = 0.2f;

        private readonly RaycastHit[] _hits = new RaycastHit[10];
        private readonly HashSet<Collider> _damageableColliders = new HashSet<Collider>();
        private bool _isDamageChecking;

        public async void StartAttack()
        {
            _isDamageChecking = false;
            _damageableColliders.Clear();
            await this.DelayInSeconds(damageDelay);
            _isDamageChecking = true;
        }

        public void StopAttack()
        {
            _isDamageChecking = false;
            _damageableColliders.Clear();
        }

        private void Update()
        {
            if (!_isDamageChecking) return;

            var numHits = Physics.RaycastNonAlloc(
                transform.position,
                transform.forward,
                _hits,
                raycastDistance,
                layerMask);
            for (int i = 0; i < numHits; i++)
            {
                var hit = _hits[i];
                if (_damageableColliders.Contains(hit.collider)) continue;
                hit.collider.gameObject.GetComponent<IDamageable>()?.TakeDamage(10);
                _damageableColliders.Add(hit.collider);
            }
        }
    }
}